package com.app.couponsharelife.base

import android.content.Intent
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.AlibcConstants
import com.alibaba.baichuan.trade.biz.context.AlibcResultType
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams
import com.alibaba.baichuan.trade.biz.login.AlibcLogin
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback
import com.bumptech.glide.manager.LifecycleListener
import com.hwangjr.rxbus.RxBus
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.ui.main.MainActivity
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.FinishActivityManager
import com.app.couponsharelife.ui.dialog.MyProgressDialog
import com.app.couponsharelife.ui.main.home.banner.ShareAwardActivity
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.main.home.search.HQTGoodsListActivity
import com.app.couponsharelife.ui.main.home.shopweb.ShopWebActivity
import com.app.couponsharelife.ui.main.home.shopweb.TaoBaoWebActivity
import com.app.couponsharelife.ui.main.home.shopweb.WebActivity
import com.app.couponsharelife.ui.main.me.experiencemen.ExperienceMenActivity
import com.app.couponsharelife.ui.main.special.BrandSpecialActivity
import com.app.couponsharelife.ui.main.special.NewManFreeActivity
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import com.app.couponsharelife.utils.ToastUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import java.util.HashMap
import java.util.concurrent.TimeUnit

/**
 * Created by guluwa on 2018/3/30.
 */

abstract class LazyFragment : Fragment(), IBaseView {
    private var pddGoodsList= arrayListOf<TaobaoGoodBean>()
    var mViewDataBinding: ViewDataBinding? = null
    private var mIsMulti = false
    private var savedState: Bundle? = null
    private var gradeID=""
    private var userPhone=""

    private var alibcShowParams: AlibcShowParams? = null//页面打开方式，默认，H5，Native
    private var exParams: HashMap<String, String>? = null//yhhpass参数
    private var alibcTaokeParams: AlibcTaokeParams? = null//淘客参数，包括pid，unionid，subPid
    /**
     * 顶部轮播图监听
     */
    var listenerTop: LifecycleListener? = null
    /**
     * 进度对话框
     */
    private var mProgressDialog: MyProgressDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        RxBus.get().register(this)
        gradeID=AppUtils.getString(Contacts.USER_GRADE_ID,"0")
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        if (mViewDataBinding == null) {
            mViewDataBinding = DataBindingUtil.inflate(inflater, viewLayoutId, container, false)
        }
        val parent = mViewDataBinding!!.root.parent
        if (parent != null) {
            (parent as ViewGroup).removeView(mViewDataBinding!!.root)
        }
        return mViewDataBinding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
    }

    open fun initViewModel() {

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        // Restore State Here
        if (!restoreStateFromArguments()) {
            // First Time, Initialize something here
            onFirstTimeLaunched()
        }
        if (userVisibleHint && mViewDataBinding != null && !mIsMulti) {
            mIsMulti = true
            lazyLoad()
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        if (isVisibleToUser && isVisible && mViewDataBinding != null && !mIsMulti) {
            mIsMulti = true
            lazyLoad()
        } else {
            super.setUserVisibleHint(isVisibleToUser)
        }
    }

    /**
     * 绑定布局文件
     *
     * @return 布局文件ID
     */
    abstract val viewLayoutId: Int

    /**
     * 初始化视图控件
     */
    protected abstract fun initViews()

    /**
     * 当视图初始化并且对用户可见的时候去真正的加载数据
     */
    protected abstract fun lazyLoad()

    /**
     * 当视图已经对用户不可见并且加载过数据，如果需要在切换到其他页面时停止加载数据，可以覆写此方法
     */
    protected fun stopLoad() {

    }

    override fun onDestroy() {
        RxBus.get().unregister(this)
        super.onDestroy()
    }

    /**
     * 弹出Toast
     */
    override fun showToastMsg(msg: String) {
        ToastUtil.getInstance().showToast(msg)
    }

    open fun onFirstTimeLaunched() {
        initViewModel()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        // Save State Here
        saveStateToArguments()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // Save State Here
        saveStateToArguments()
    }

    private fun saveStateToArguments() {
        if (view != null)
            savedState = saveState()
        if (savedState != null) {
            arguments?.putBundle("internalSavedViewState8954201239547", savedState)
        }
    }

    private fun restoreStateFromArguments(): Boolean {
        savedState = arguments?.getBundle("internalSavedViewState8954201239547")
        if (savedState != null) {
            restoreState()
            return true
        }
        return false
    }

    private fun restoreState() {
        if (savedState != null) {
            onRestoreState(savedState!!)
        }
    }

    open fun onRestoreState(savedInstanceState: Bundle) {
        initViewModel()
    }

    private fun saveState(): Bundle {
        val state = Bundle()
        onSaveState(state)
        return state
    }

    open fun onSaveState(outState: Bundle) {

    }

    /*override fun showProgressDialog(msg: String) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog(context,R.style.ProgressDialogStyle)
            mProgressDialog!!.setCancelable(false)
            mProgressDialog!!.setProgressStyle(ProgressDialog.STYLE_SPINNER)
        }
        mProgressDialog!!.setMessage(msg)
        mProgressDialog!!.show()
    }*/
    override fun showProgressDialog(msg: String) {
        if (mProgressDialog == null) {
            mProgressDialog = MyProgressDialog(context!!,R.style.ProgressDialogStyle,msg)
            mProgressDialog!!.setCancelable(false)
        }
        mProgressDialog!!.show()
    }
    override fun dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog!!.dismiss()
        }
    }

    private var disposableCountDown: Disposable? = null

    fun showCountDownProgressDialog(msg: String, num: Long) {
        showProgressDialog(msg)
        disposableCountDown = Observable.interval(0, num, TimeUnit.SECONDS)// 倒计时
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ aLong ->
                    if (aLong != 0L) {
                        dismissProgressDialog()
                        disposableCountDown?.dispose()
                        disposableCountDown = null
                    }
                }) {
                    dismissProgressDialog()
                    disposableCountDown?.dispose()
                    disposableCountDown = null
                }
    }

    fun judgeAdzoneIdExist(): Boolean {
        return if (AppUtils.getString(Contacts.ADZONE_ID, "") == "") {
            showToastMsg("用户信息异常，请重新登录")
            AppUtils.setString(Contacts.TOKEN, "")
            AppUtils.setString(Contacts.USERTYPE, "")
            AppUtils.setString(Contacts.USERID, "")
            AppUtils.setString(Contacts.ADZONE_ID, "")
            val finishActivityManager = FinishActivityManager.getInstance()
            startActivity(Intent(finishActivityManager.currentActivity()!!, MainActivity::class.java))
            finishActivityManager.finishAllActivity()
            false
        } else true
    }

    /**
     * 异常数据解析
     */
    open fun parseErrorDate(msg: String): PageTipBean {
        return when {
            msg == "没有网络" -> PageTipBean("您的网络跑到外星球去了", R.drawable.ic_no_network, 1)
            msg.contains("IllegalStateException") -> PageTipBean("数据格式错误", R.drawable.ic_data_empty, 1)
            else -> PageTipBean(msg, R.drawable.ic_data_empty, 1)
        }
    }
    fun registerLifeListenerTop(listener: LifecycleListener) {
        this.listenerTop = listener
        listenerTop?.onStart()
    }
    fun setBannerClic(topBanner: TopBanner){
        when(topBanner.jumpType){
            "SHOU_XI"->{  //首席
                startActivity(Intent(activity, ExperienceMenActivity::class.java))
                /*if (gradeID.toLong()<3) {  //不是首席
                    userPhone=AppUtils.getString(Contacts.USER_MOBILE,"")
                    if (userPhone.isEmpty()){
                        val intent=Intent(activity, BindPhoneNumActivity::class.java)
                        intent.putExtra("Type","Choiceness")
                        startActivity(intent)
                    }else{
                        startActivity(Intent(activity, ExperienceMenActivity::class.java))
                    }
                }*/
            }
            "LINKE"->{  //H5
                val intent=Intent(activity, ShopWebActivity::class.java)
                intent.putExtra("url", topBanner.link)
                intent.putExtra("name", topBanner.name?:"")
                startActivity(intent)
            }
            "PRODUCT"->{  //分类商品
                val intent= Intent(activity, HQTGoodsListActivity::class.java)
                intent.putExtra("FavoritesID",topBanner.favoritesId)
                intent.putExtra("Name",topBanner.name)
                startActivity(intent)
            }
            "PDD_GOODS"->{  //胸膜PIN_SHOU_QI
                if (pddGoodsList.isNotEmpty()){
                    setIntent(pddGoodsList[0])
                }else{
                    getGoodsList(topBanner.link!!)
                }
            }
            "PIN_SHOU_QI"->{  //分享得好礼
                val intent= Intent(activity, ShareAwardActivity::class.java)
                startActivity(intent)
            }
            "NEWMENFREE" -> {//新人0元购
                val intent = Intent(activity, NewManFreeActivity::class.java)
                intent.putExtra("FavoritesID",topBanner.favoritesId?:"")
                intent.putExtra("Name",topBanner.name)
                startActivity(intent)
            }
            "BRANDTHEME" -> {//品牌专场
                startActivity(Intent(activity, BrandSpecialActivity::class.java))
            }
            "SDK_LINK" -> {
                //goTaoBao(url)
                val relationId = AppUtils.getString(Contacts.ADZONE_ID, "")
                if (relationId.isNotEmpty()) {
                    //val relationId=AppUtils.getString(Contacts.ADZONE_ID, "")
                    /*intent = Intent(activity, TaoBaoWebActivity::class.java)
                    intent.putExtra("url", url + "&relationId=${relationId}")
                    intent.putExtra("name", name)*/
                    goTaoBao(topBanner.link + "&relationId=${relationId}")
                } else {
                    //getAliLonginUrl()
                    taobaoLogin()
                }
            }
            "SDK_H5" -> {
                val relationId = AppUtils.getString(Contacts.ADZONE_ID, "")
                if (relationId.isNotEmpty()) {
                    //val relationId=AppUtils.getString(Contacts.ADZONE_ID, "")
                    val intent = Intent(activity, TaoBaoWebActivity::class.java)
                    intent.putExtra("url", topBanner.link + "&relationId=${relationId}")
                    intent.putExtra("name", topBanner.name?:"")
                    startActivity(intent)
                    //goTaoBao(topBanner.link + "&relationId=${relationId}")
                } else {
                    //getAliLonginUrl()
                    taobaoLogin()
                }
            }
            else->{  //H5

            }
        }
    }
    private fun taobaoLogin(){
        showProgressDialog("请稍后")
        val alibcLogin = AlibcLogin.getInstance()
        alibcLogin.showLogin(object : AlibcLoginCallback {
            override fun onSuccess(p0: Int) {
                //showToastMsg("登录成功 ")
                //获取淘宝用户信息
                //Log.i("eee", "获取淘宝用户信息: "+AlibcLogin.getInstance().session)
                dismissProgressDialog()
                //getAliLoginUrl()
                getAliLonginUrl()
            }

            override fun onFailure(p0: Int, p1: String?) {
                //showToastMsg("登录失败")
                dismissProgressDialog()
            }
        })
    }
    private fun goTaoBao(url:String) {
        showCountDownProgressDialog("请稍候", 3)
        alibcShowParams = AlibcShowParams(OpenType.Native, false)
        exParams = HashMap()
        exParams!![AlibcConstants.ISV_CODE] = "appisvcode"
        exParams!!["alibaba"] = "阿里巴巴"//自定义参数部分，可任意增删改
        // 若非淘客taokeParams设置为null即可
        val pid = Contacts.ALIMAMA_PID //+ AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams = AlibcTaokeParams()
        alibcTaokeParams?.adzoneid = "65231850041"//AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams?.pid = pid
        alibcTaokeParams?.subPid = pid
        alibcTaokeParams?.extraParams = HashMap()
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["taokeAppkey"] = Contacts.APP_ID
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["relationId"] = AppUtils.getString(Contacts.ADZONE_ID, "")
        if (url == "") {
            showToastMsg("该商品暂时不能购买")
            return
        }
        val rlid="&relationId=${AppUtils.getString(Contacts.ADZONE_ID, "")}"
        AlibcTrade.show(activity, AlibcPage(url+rlid), alibcShowParams, alibcTaokeParams, exParams, object : AlibcTradeCallback {
            override fun onTradeSuccess(tradeResult: AlibcTradeResult) {
                //当addCartPage加购成功和其他page支付成功的时候会回调
                if (tradeResult.resultType == AlibcResultType.TYPECART) {
                    //加购成功
                    showToastMsg("加购成功")
                } else if (tradeResult.resultType == AlibcResultType.TYPEPAY) {
                    //支付成功
//                    Log.d("order", tradeResult.payResult.paySuccessOrders[0])
                }
            }

            override fun onFailure(errCode: Int, errMsg: String) {
                showToastMsg("电商SDK出错,错误码=$errCode / 错误消息=$errMsg")
            }
        })
    }
    private fun getGoodsList(goodsId:String){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["goodsId"]= goodsId
        RetrofitWorker.retrofitWorker.getPDDGoodsList(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().pddData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<PDDGoodsListBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<PDDGoodsListBean>) {
                        dismissProgressDialog()
                        if (it.data!=null&&it.data!!.recordss!!.isNotEmpty()){
                            pddGoodsList.clear()
                            pddGoodsList.addAll(it.data!!.recordss!!)
                            setIntent(pddGoodsList[0])
                        }else{

                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun getAliLonginUrl(){
        showProgressDialog("加载中...")
        val map = HashMap<String, String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getAuthUrl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            val url=it.data?:""
                            if (url.isNotEmpty()){
                                val intent= Intent(context, WebActivity::class.java)
                                intent.putExtra("url", url)
                                intent.putExtra("name", "淘宝授权")
                                startActivity(intent)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            if ("502"==e.code.toString()){

                            }else{
                                showToastMsg(e.msg)
                            }
                        }else{
                            showToastMsg("数据加载出错！")
                        }
                    }
                })
    }
    private fun setIntent(taobaoGoodBean:TaobaoGoodBean){
        val intent = Intent(context, GoodDetailActivity::class.java)
        intent.putExtra("good", taobaoGoodBean)
        startActivity(intent)
    }
}